#!/bin/bash

# centos7 everything iso文件路径
ISO_FILE="/root/CentOS-7-x86_64-Everything-2207-02.iso"
# 挂载路径
MOUNT_POINT="/media"
#挂载选项，1是永久挂载，2是临时挂载
MOUNT_FLAG=1

color() {
    local message="$1"
    local status="$2"
    local message_length=${#message}
    local terminal_width=$(tput cols)
    local middle_column=$(( terminal_width / 2))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf '%s\n\033[%sG' "$message"  "$middle_column"
    # Print the status message
    printf "["
    case $status in
        success|0)
            printf "$SETCOLOR_SUCCESS"
            printf "  OK  "
            ;;
        failure|1)
            printf "$SETCOLOR_FAILURE"
            printf "FAILED"
            ;;
        *)
            printf "$SETCOLOR_WARNING"
            printf "WARNING"
            ;;
    esac
    printf "$SETCOLOR_NORMAL"
    printf "]\n"
}

temp_mount () {
	mount -o loop $ISO_FILE $MOUNT_POINT && color "已将$ISO_FILE 临时挂载到 $MOUNT_POINT" 0 \
	|| color "$ISO_FILE 临时挂载${MOUNT_POINT}失败。" 1
}

permanent_mount () {
	if  grep "$MOUNT_POINT\|$ISO_FILE" /etc/fstab &> /dev/null;then
		color "/etc/fstab已存在指定的挂载信息！" 1
		exit
	else
		echo "$ISO_FILE $MOUNT_POINT iso9660 loop 0 0" >> /etc/fstab
		mount -a && color "已将$ISO_FILE 永久挂载到 $MOUNT_POINT" 0 || color "$ISO_FILE 临时挂载${MOUNT_POINT}失败。" 1
	fi
	
}	

config_yum () {
	if [ ! -d /etc/yum.repos.d/bak ];then
		mkdir -p /etc/yum.repos.d/bak && color "创建/etc/yum.repos.d/bak 文件夹." 0
	fi
	mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak/ && color "移动原始repo文件到bak目录." 0
	cat > /etc/yum.repos.d/local_yum.repo <<-EOF
	[local_media]
	name=CentOS-\$releasever - Media
	baseurl=file:///media/
	        file:///media/cdrom/
	        file:///media/cdrecorder/
	gpgcheck=1
	enabled=1
	gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
	EOF
	yum clean all
	yum makecache
	yum repolist all && color "本地yum源配置完成." 0
}


case $MOUNT_FLAG in 
	1)
		permanent_mount	
	;;
	2)
		temp_mount
	;;
	*)
		color  "错误的MOUNT_FLAG变量" 1
esac

config_yum
